package com.lizhenhua.fmmall.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.lizhenhua.fmmall.service.serviceImpl.OrderServiceImpl;
import com.lizhenhua.fmmall.websocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.Session;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

//  回调接口
@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrderServiceImpl orderService;

    /**
     * 用户支付成功之后，微信支付平台就会调用这个接口，将支付状态的数据穿回来
     * 接受微信支付平台传输的数据
     * 他的数据是xml 格式 （使用request的输入流来接受 ）
     */
    @RequestMapping("/callback")
    public String success(HttpServletRequest request) throws IOException {


        try {

            // 接受微信平台传过来的数据
            ServletInputStream inputStream = request.getInputStream();
            byte[] bytes = new byte[1024];
            StringBuilder builder = new StringBuilder();
            int len = -1;
            while ((len = inputStream.read(bytes)) != -1) {
                builder.append(new String(bytes, 0, len));
            }
            String s = builder.toString();
            // 将xml文件接口的字符串 转换为 map 格式
            // 标签名 作为key  对应的值 作为value  穿过来的
            Map<String, String> stringStringMap = WXPayUtil.xmlToMap(s);
            String orderId = stringStringMap.get("out_trade_no");
            //equalsIgnoreCase 忽略大小写的比较
            if (stringStringMap != null && "SUCCESS".equalsIgnoreCase(stringStringMap.get("result_code"))) {
                System.out.println("----------------------------orderId:"+stringStringMap.get("out_trade_no"));
                // 这里面表示支付成功
                // 2. 修改订单状态 "代发货/已支付"
                int i = orderService.updateOrderStatus(orderId, "2");

                // 3.通过websocket连接 向前端推送消息
                // sendMsg是 WebSocketServer 下的方法
                 WebSocketServer.sendMsg(orderId,"1");


                if (i >0) {
                    // 4. 响应微信支付平台
                    HashMap<String, String> resp = new HashMap<>();
                    WXPayUtil.mapToXml(resp);
                    resp.put("return_code", "success");
                    resp.put("return_message", "OK");
                    resp.put("appid", stringStringMap.get("appid"));
                    resp.put("result_code", "success");
                    return WXPayUtil.mapToXml(resp);
                }else {
                    return  null;
                }
            } else {
                // 支付失败
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
